/**
 * 2014/06/14 由于接口服务器已提供“我的通知“的数据，删除生成“我的通知”的测试数据的代码
 * @author 程文智
 */
package com.main.taxsystem;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;

import com.main.taxsystem.TableInfoSet.AlreadyAnswerQuestionTableInfo;
import com.main.taxsystem.TableInfoSet.BranchMapTableInfo;
import com.main.taxsystem.TableInfoSet.MyQestionTableInfo;
import com.main.taxsystem.TableInfoSet.PersonalNoticesTableInfo;
import com.main.taxsystem.TableInfoSet.TestDataTableInfo;

public class TaxSystemContentProvider extends ContentProvider {
	public static final String TAG = "TaxSystemContentProvider";
	private static final String BASE_URI = "com.taxsystem.contentprovider";
	
	//我的通知 - 程文智
	public static final Uri URI_PERSIONAL_NOTICES = Uri.parse("content://com.taxsystem.contentprovider/personal_notices");
	private static final int PERSIONAL_NOTICES_ALLROWS =11;
	private static final int PERSIONAL_NOTICES_SINGLE_ROW=12;
	
	//亮利
	public static final Uri URI_ALREADY_ANSWER_QUESTION = 
			Uri.parse("content://"+BASE_URI+"/already_answer_question");
	private static final int ALREADY_ANSWER_QUESTION_ALLROWS = 21;
	private static final int ALREADY_ANSWER_QUESTION_SINGLE_ROW =22;
	
	//我的提问 - 亮利
	public static final Uri URI_MY_QUESTION =
			Uri.parse("content://"+BASE_URI+"/my_question");
	private static final int MY_QUESTION_ALLROW = 31;
	private static final int MY_QUESTION_SINGLE_ROW = 32;
	
	
	//办税地图 - 程文智
	public static final Uri URI_BRANCH_MAP = Uri.parse("content://"+BASE_URI+"/branch_map");
	private static final int BRANCH_MAP_ALLROWS = 41;
	private static final int BRANCH_MAP_SINGLE_ROW = 42;
	
	//测试数据Uri
	public static final Uri URI_TEST_DATA = 
			Uri.parse("content://"+BASE_URI+"/test_data");
	private static final int TEST_DATA_ALLROW = 881;
	private static final int TEST_DATA_SINGLE_ROW = 882;
	
	
	private TaxSystemSQLiteOpenHelper DBOpenHelper;
	
	private static final UriMatcher uriMatcher;
	static{
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(BASE_URI, "personal_notices", PERSIONAL_NOTICES_ALLROWS);
		uriMatcher.addURI(BASE_URI,"personal_notices/*",PERSIONAL_NOTICES_SINGLE_ROW);
		uriMatcher.addURI(BASE_URI, "already_answer_question", ALREADY_ANSWER_QUESTION_ALLROWS);
		uriMatcher.addURI(BASE_URI, "already_answer_question/*", ALREADY_ANSWER_QUESTION_SINGLE_ROW);
		uriMatcher.addURI(BASE_URI, "my_question", MY_QUESTION_ALLROW);
		uriMatcher.addURI(BASE_URI, "my_question/*", MY_QUESTION_SINGLE_ROW);
		uriMatcher.addURI(BASE_URI,"test_data",TEST_DATA_ALLROW);
		uriMatcher.addURI(BASE_URI, "test_data/*", TEST_DATA_SINGLE_ROW);
		uriMatcher.addURI(BASE_URI,"branch_map",BRANCH_MAP_ALLROWS);
		uriMatcher.addURI(BASE_URI, "branch_map/*", BRANCH_MAP_SINGLE_ROW);
	}
	public TaxSystemContentProvider() {
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = DBOpenHelper.getWritableDatabase();;
		TableInfo tableInfo = null;
		Uri tableUri = null;
		
		switch(uriMatcher.match(uri)){
		case PERSIONAL_NOTICES_SINGLE_ROW:
		case PERSIONAL_NOTICES_ALLROWS:{
			tableInfo =PersonalNoticesTableInfo.getInstance();
			tableUri = URI_PERSIONAL_NOTICES;
			break;
		}
		case ALREADY_ANSWER_QUESTION_ALLROWS:
		case ALREADY_ANSWER_QUESTION_SINGLE_ROW:{
			tableInfo = AlreadyAnswerQuestionTableInfo.getInstance();
			tableUri = URI_ALREADY_ANSWER_QUESTION;
			break;
		}
		case MY_QUESTION_ALLROW:
		case MY_QUESTION_SINGLE_ROW:{
			tableInfo = MyQestionTableInfo.getInstance();
			tableUri = URI_MY_QUESTION;
			break;
		}
		case BRANCH_MAP_ALLROWS:
		case BRANCH_MAP_SINGLE_ROW:{
			tableInfo = BranchMapTableInfo.getInstance();
			tableUri = URI_BRANCH_MAP;
			break;
		}
		default:{
			Log.e(TAG,"insert() 錯誤的Uri");
			return null;
		}
		}
		
		Log.v(TAG,"insert(): "+uri.toString());
		long id = db.insert(tableInfo.getTableName(), null, values);
		if(id>-1){
			Uri insertedId = ContentUris.withAppendedId(tableUri, id);
			getContext().getContentResolver().notifyChange(insertedId, null);
			Log.v(TAG,"insert(): notifyChange()");
			return insertedId;
		}
		return null;
	}

	public boolean onCreate() {
		DBOpenHelper = new TaxSystemSQLiteOpenHelper(getContext(), 
				TaxSystemSQLiteOpenHelper.DB_NAME, null, TaxSystemSQLiteOpenHelper.DB_VERSION);
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		Log.v(TAG,"query() begin");
		Log.v(TAG,"Uri="+uri.toString());
		//Open database
		SQLiteDatabase db;
		
		try{
			db = DBOpenHelper.getWritableDatabase();
		}catch (SQLiteException e){
			db = DBOpenHelper.getReadableDatabase();
		}
		
		TableInfo tableInfo=null;
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

		switch(uriMatcher.match(uri)){
		case PERSIONAL_NOTICES_ALLROWS:{
			Log.v(TAG,"query(): PERSIONAL_NOTICES_ALLROWS");
			tableInfo = PersonalNoticesTableInfo.getInstance();
			break;
		}
		case PERSIONAL_NOTICES_SINGLE_ROW: {
			Log.v(TAG,"query(): PERSIONAL_NOTICES_SINGLE_ROW:"+uri.getPathSegments().get(1));
			String notationId = uri.getPathSegments().get(1);
			queryBuilder.appendWhere("notationId" + "=" + notationId);
			tableInfo = PersonalNoticesTableInfo.getInstance();
			break;
		}
		case TEST_DATA_ALLROW: {
			Log.v(TAG,"query(): TEST_DATA_ALLROWS");
			tableInfo  = TestDataTableInfo.getInstance();
			break;
		}
		case TEST_DATA_SINGLE_ROW:{
			Log.v(TAG,"query(): PERSIONAL_NOTICES_SINGLE_ROW:"+uri.getPathSegments().get(1));
			tableInfo = TestDataTableInfo.getInstance();
			String id = uri.getPathSegments().get(1);
			queryBuilder.appendWhere("id="+id);
			break;
		}
		case ALREADY_ANSWER_QUESTION_ALLROWS:{
			Log.v(TAG,"query(): MY_QUESTION_ALLROW");
			tableInfo = TableInfoSet.AlreadyAnswerQuestionTableInfo.getInstance();
			break;
		}
		case ALREADY_ANSWER_QUESTION_SINGLE_ROW:{
			Log.v(TAG,"query(): MY_QUESTION_SINGLE_ROW:"+uri.getPathSegments().get(1));
			tableInfo = AlreadyAnswerQuestionTableInfo.getInstance();
			String questionId = uri.getPathSegments().get(1);
			queryBuilder.appendWhere(AlreadyAnswerQuestionTableInfo.COLUMN_NAME_QUESTION_ID+"="+questionId);
			break;
		}
		case MY_QUESTION_ALLROW:{
			Log.v(TAG,"query(): MY_QUESTION_ALLROW");
			tableInfo = MyQestionTableInfo.getInstance();
			break;
		}
		case MY_QUESTION_SINGLE_ROW:{
			Log.v(TAG,"query(): MY_QUESTION_SINGLE_ROW:"+uri.getPathSegments().get(1));
			tableInfo = MyQestionTableInfo.getInstance();
			String questionId = uri.getPathSegments().get(1);
			queryBuilder.appendWhere(MyQestionTableInfo.COLUMN_NAME_QUESTION_ID+"="+questionId);
			break;
		}
		case BRANCH_MAP_ALLROWS:{
			Log.v(TAG,"query(): BRANCH_MAP_ALLROWS");
			tableInfo = BranchMapTableInfo.getInstance();
			break;
		}
		case BRANCH_MAP_SINGLE_ROW:{
			Log.v(TAG,"query(): BRANCH_MAP_SINGLE_ROW:"+uri.getPathSegments().get(1));
			tableInfo = BranchMapTableInfo.getInstance();
			String questionId = uri.getPathSegments().get(1);
			queryBuilder.appendWhere(MyQestionTableInfo.COLUMN_NAME_QUESTION_ID+"="+questionId);
			break;
		}
		default:{
			Log.e(TAG,"query():錯誤的Uri");
			return null;
		}
		}
		
		queryBuilder.setTables(tableInfo.getTableName());
		Cursor cursor = queryBuilder.query(db, projection, selection, null, null, null,null);
		Log.v(TAG,"cursor:"+(cursor.getCount()));
		
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		Log.v(TAG,"TaxSystemContentProvider::update()");
		TableInfo info = tableMatcher(uri);
		SQLiteDatabase db = DBOpenHelper.getWritableDatabase();
		
		int updateCount = db.update(info.getTableName(), values, selection, selectionArgs);
		getContext().getContentResolver().notifyChange(uri, null);
		return updateCount;
	}
	
	private TableInfo tableMatcher(Uri uri){
		TableInfo tableInfo = null;
		switch(uriMatcher.match(uri)){
		case PERSIONAL_NOTICES_ALLROWS:{
			Log.v(TAG,"tableMatcher(): PERSIONAL_NOTICES_ALLROWS");
			tableInfo = PersonalNoticesTableInfo.getInstance();
			break;
		}
		case PERSIONAL_NOTICES_SINGLE_ROW: {
			Log.v(TAG,"tableMatcher(): PERSIONAL_NOTICES_SINGLE_ROW:"+uri.getPathSegments().get(1));
			String notationId = uri.getPathSegments().get(1);
			tableInfo = PersonalNoticesTableInfo.getInstance();
			break;
		}
		case TEST_DATA_ALLROW: {
			Log.v(TAG,"tableMatcher(): TEST_DATA_ALLROWS");
			tableInfo  = TestDataTableInfo.getInstance();
			break;
		}
		case TEST_DATA_SINGLE_ROW:{
			Log.v(TAG,"tableMatcher(): PERSIONAL_NOTICES_SINGLE_ROW:"+uri.getPathSegments().get(1));
			tableInfo = TestDataTableInfo.getInstance();
			String id = uri.getPathSegments().get(1);
			break;
		}
		case ALREADY_ANSWER_QUESTION_ALLROWS:{
			Log.v(TAG,"tableMatcher(): MY_QUESTION_ALLROW");
			tableInfo = TableInfoSet.AlreadyAnswerQuestionTableInfo.getInstance();
			break;
		}
		case ALREADY_ANSWER_QUESTION_SINGLE_ROW:{
			Log.v(TAG,"tableMatcher(): MY_QUESTION_SINGLE_ROW:"+uri.getPathSegments().get(1));
			tableInfo = AlreadyAnswerQuestionTableInfo.getInstance();
			String questionId = uri.getPathSegments().get(1);
			break;
		}
		case MY_QUESTION_ALLROW:{
			Log.v(TAG,"tableMatcher(): MY_QUESTION_ALLROW");
			tableInfo = MyQestionTableInfo.getInstance();
			break;
		}
		case MY_QUESTION_SINGLE_ROW:{
			Log.v(TAG,"tableMatcher(): MY_QUESTION_SINGLE_ROW:"+uri.getPathSegments().get(1));
			tableInfo = MyQestionTableInfo.getInstance();
			String questionId = uri.getPathSegments().get(1);
			break;
		}
		case BRANCH_MAP_ALLROWS:{
			Log.v(TAG,"tableMatcher(): BRANCH_MAP_ALLROWS");
			tableInfo = BranchMapTableInfo.getInstance();
			break;
		}
		case BRANCH_MAP_SINGLE_ROW:{
			Log.v(TAG,"query(): BRANCH_MAP_SINGLE_ROW:"+uri.getPathSegments().get(1));
			tableInfo = BranchMapTableInfo.getInstance();
			String questionId = uri.getPathSegments().get(1);
			break;
		}
		default:{
			Log.e(TAG,"tableMatcher():錯誤的Uri");
			return null;
		}
		}
		return tableInfo;
	}
	
	private static class TaxSystemSQLiteOpenHelper extends SQLiteOpenHelper {
		private static final String TAG ="NoticesSQLiteOpenHelper";
		public static final String DB_NAME="TaxSystem.db";
		public static final String KEY_ID = "_id";
		private static final int DB_VERSION = 1;
		private SQLiteDatabase database;

		public TaxSystemSQLiteOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
		}

		public TaxSystemSQLiteOpenHelper(Context context, String name,
				CursorFactory factory, int version,
				DatabaseErrorHandler errorHandler) {
			super(context, name, factory, version, errorHandler);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			Log.v(TAG,"onCreate() begin");
			database = db;
			db.execSQL(buildSQLTableCreate(PersonalNoticesTableInfo.getInstance()));
			db.execSQL(buildSQLTableCreate(TableInfoSet.TestDataTableInfo.getInstance()));
			db.execSQL(buildSQLTableCreate(TableInfoSet.AlreadyAnswerQuestionTableInfo.getInstance()));
			db.execSQL(buildSQLTableCreate(TableInfoSet.MyQestionTableInfo.getInstance()));
			db.execSQL(buildSQLTableCreate(TableInfoSet.BranchMapTableInfo.getInstance()));
			addData();
		}

		private void addData() {
			addTestData();
			addAlreadyAnswerQuestionData();
			addMyQuestionData();
			addBranchMapData();
		}

		private void addAlreadyAnswerQuestionData(){
			if(database==null)
				Log.e(TAG,"addAlreadyAnswerQuestionData():database is null");
			
			String content = "测试内容要";
			for(int i=0;i<5;++i){
				content += "长长长长长长长长长长长长长长长长长长长长长长长长";
			}
			ContentValues values = null;
			for(int i=0;i<7;++i){
				values = new ContentValues();
				values.put(AlreadyAnswerQuestionTableInfo.COLUMN_NAME_QUESTION_ID, i+1);
				values.put(AlreadyAnswerQuestionTableInfo.COLUMN_NAME_QUESTION_TITLE, "测试通知 "+(i+1));
				values.put(AlreadyAnswerQuestionTableInfo.COLUMN_NAME_CREATE_TIME, "1999-09-0"+(i+1));
				values.put(AlreadyAnswerQuestionTableInfo.COLUMN_NAME_ANSWER_CONTENT, content);
				database.insert(AlreadyAnswerQuestionTableInfo.TABLE_NAME, null, values);
			}
		}
		
		private void addMyQuestionData(){
			if(database==null)
				Log.e(TAG,"addMyQuestionData():database is null");
			
			String content = "测试内容要";
			for(int i=0;i<5;++i){
				content += "长长长长长长长长长长长长长长长长长长长长长长长长";
			}
			ContentValues values = null;
			for(int i=0;i<7;++i){
				values = new ContentValues();
				values.put(MyQestionTableInfo.COLUMN_NAME_QUESTION_ID,i+1);
				values.put(MyQestionTableInfo.COLUMN_NAME_QUESTION_TITLE, "测试通知 "+(i+1));
				values.put(MyQestionTableInfo.COLUMN_NAME_UNREAD, false);
				values.put(MyQestionTableInfo.COLUMN_NAME_ANSWER_COUNT, i+5);
				values.put(MyQestionTableInfo.COLUMN_NAME_CREATE_TIME, "1998-08-0"+i+2);
				database.insert(MyQestionTableInfo.TABLE_NAME, null, values);
			}
		}
		
		private void addTestData() {
			if(database==null)
				Log.e(TAG,"addNoticeTestData():database is null");
			
			String content = "测试内容要";
			for(int i=0;i<5;++i){
				content += "长长长长长长长长长长长长长长长长长长长长长长长长";
			}
			ContentValues values = null;
			for(int i=0;i<7;++i){
				values = new ContentValues();
				values.put(TestDataTableInfo.COLUMN_NAME_TITLE, "测试通知 "+(i+1));
				values.put(TestDataTableInfo.COLUMN_NAME_CONTENT, content);
				values.put(TestDataTableInfo.COLUMN_NAME_ID, i+1);
				values.put(TestDataTableInfo.COLUMN_NAME_CREATE_TIME,"2016年6月1"+i+"日");
				database.insert(TestDataTableInfo.TABLE_NAME, null, values);
			}
		}
		
		private void addBranchMapData() {
			if(database==null)
				Log.e(TAG,"addBranchMapData():database is null");
			ContentValues values = null;
			String branchId = null;
			String branchName = null;
			String address = null;
			String longitude = null;
			String latitude = null;
			String distance = "526米";
			
			values = new ContentValues();
			branchId = "111";
			branchName = "苏州地方税务局";
			address = "江苏省苏州市姑苏区干将西路535";
			longitude = "11.221";
			latitude = "12.221";
			
			values.put(BranchMapTableInfo.COLUMN_NAME_BRANCH_ID, branchId);
			values.put(BranchMapTableInfo.COLUMN_NAME_BRANCH_NAME, branchName);
			values.put(BranchMapTableInfo.COLUMN_NAME_ADDRESS, address);
			values.put(BranchMapTableInfo.COLUMN_NAME_LONGITUDE, longitude);
			values.put(BranchMapTableInfo.COLUMN_NAME_LATITUDE, latitude);
			values.put(BranchMapTableInfo.COLUMN_NAME_DISTANCE, distance);
			database.insert(BranchMapTableInfo.TABLE_NAME, null, values);
			
			values = new ContentValues();
			branchId = "222";
			branchName = "苏州市地税局第一税务分局";
			address = "江苏省苏州市姑苏区干将西路535";
			longitude = "11.221";
			latitude = "12.221";
			values.put(BranchMapTableInfo.COLUMN_NAME_BRANCH_ID, branchId);
			values.put(BranchMapTableInfo.COLUMN_NAME_BRANCH_NAME, branchName);
			values.put(BranchMapTableInfo.COLUMN_NAME_ADDRESS, address);
			values.put(BranchMapTableInfo.COLUMN_NAME_LONGITUDE, longitude);
			values.put(BranchMapTableInfo.COLUMN_NAME_LATITUDE, latitude);
			values.put(BranchMapTableInfo.COLUMN_NAME_DISTANCE, distance);
			database.insert(BranchMapTableInfo.TABLE_NAME, null, values);
			
			values = new ContentValues();
			branchId = "333";
			branchName = "苏州市地税局第二税务分局";
			address = "江苏省苏州市姑苏区带城桥路88";
			longitude = "11.221";
			latitude = "12.221";
			values.put(BranchMapTableInfo.COLUMN_NAME_BRANCH_ID, branchId);
			values.put(BranchMapTableInfo.COLUMN_NAME_BRANCH_NAME, branchName);
			values.put(BranchMapTableInfo.COLUMN_NAME_ADDRESS, address);
			values.put(BranchMapTableInfo.COLUMN_NAME_LONGITUDE, longitude);
			values.put(BranchMapTableInfo.COLUMN_NAME_LATITUDE, latitude);
			values.put(BranchMapTableInfo.COLUMN_NAME_DISTANCE, distance);
			database.insert(BranchMapTableInfo.TABLE_NAME, null, values);
			
			values = new ContentValues();
			branchId = "444";
			branchName = "苏州市地税局第三税务分局";
			address = "江苏省苏州市姑苏区干将西路535";
			longitude = "11.221";
			latitude = "12.221";
			values.put(BranchMapTableInfo.COLUMN_NAME_BRANCH_ID, branchId);
			values.put(BranchMapTableInfo.COLUMN_NAME_BRANCH_NAME, branchName);
			values.put(BranchMapTableInfo.COLUMN_NAME_ADDRESS, address);
			values.put(BranchMapTableInfo.COLUMN_NAME_LONGITUDE, longitude);
			values.put(BranchMapTableInfo.COLUMN_NAME_LATITUDE, latitude);
			values.put(BranchMapTableInfo.COLUMN_NAME_DISTANCE, distance);
			database.insert(BranchMapTableInfo.TABLE_NAME, null, values);
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF IT EXISTS "+PersonalNoticesTableInfo.TABLE_NAME);
			onCreate(db);
		}

		private String buildSQLTableCreate(TableInfo info){
			String createStr = "create table "+ info.getTableName()+ " ("+
					KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, ";
			String[] columns = info.getColumns();
			for(int i=0;i<columns.length-1;++i){
				createStr += columns[i] + " , ";
			}
			createStr += columns[columns.length-1];
			createStr += " );";
			Log.v(TAG,"TaxSystemSQLiteOpenHelper:buildSQLTableCreate():"+createStr);
			return createStr;
		}
	}
	
}
